<script setup lang="ts">
import { getProject } from '@/api/exam/project';
import { QuestionType } from '@/api/exam/template/types';
import { ProjectVO } from '@/api/exam/project/types';
import { addAnswer, listAnswerByProject, tempSave, updateAnswer } from '@/api/exam/answer';
import { AnswerVO } from '@/api/exam/answer/types';
import { UAParser } from 'ua-parser-js';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { exam_question_type } = toRefs<any>(proxy?.useDict('exam_question_type'));
const route = useRoute();

const project = ref<any | ProjectVO>(
  {
    survey: {
      children: []
    },
    setting: {
      answerSetting: {
        onePageOneQuestion: false
      },
      submittedSetting: {},
      examSetting: {}
    }
  }
);
const loading = ref(false);
// 分页状态
const currentPage = ref(0);

// 在创建答卷前显示
const showAnswer = ref(false);

const getProjectInfo = async (id: string) => {
  loading.value = true;
  const res = await getProject(id);
  project.value = res.data;
  loading.value = false;
};
const answerInfo = ref<AnswerVO>(null);
const answerLoading = ref(false);
const answerDisabled = computed(() => {
  const examSetting = project.value.setting.examSetting;
  let disabled = false;

  // 项目状态
  if (project.value.status === '0') {
    return disabled = true;
  }
  // 超过答题次数限制
  if (examSetting.loginLimit) {
    return disabled = answerTotal.value >= examSetting.loginLimit;
  }

  // 考试未开始：当前时间 < 开始时间 → 禁用
  if (examSetting.startTime) {
    const startTime = new Date(examSetting.startTime);
    return disabled = disabled || new Date() < startTime;
  }

  // 考试已结束：当前时间 > 结束时间 → 禁用
  if (examSetting.endTime) {
    const endTime = new Date(examSetting.endTime);
    return disabled = disabled || new Date() > endTime;
  }

  return disabled;
});
const handleAnswer = async () => {
  answerLoading.value = true;
  await getAnswerInfo();
  answerLoading.value = false;
  showAnswer.value = true;
};

// 获取答卷信息
const answerTotal = ref(0);
const getAnswerList = async () => {
  const res = await listAnswerByProject({ projectId: route.params.id });
  answerTotal.value = res.data.length;
};
const getAnswerInfo = async () => {
  const res = await addAnswer(project.value);
  answerInfo.value = res.data;
  getAnswer();
  getMetaInfo();
  tempAnswerToAnswer(answerInfo.value);
  await tempSave(answerInfo.value);
};
// 获取基本信息
const getMetaInfo = () => {
  const parser = new UAParser();
  const result = parser.getResult();
  if (answerInfo.value.metaInfo.clientInfo.browser === null) {
    answerInfo.value.metaInfo.clientInfo.browser = result.browser.name;
  }
  if (answerInfo.value.metaInfo.clientInfo.browserVersion === null) {
    answerInfo.value.metaInfo.clientInfo.browserVersion = result.browser.version;
  }
  if (answerInfo.value.metaInfo.clientInfo.platform === null) {
    answerInfo.value.metaInfo.clientInfo.platform = result.os.name;
  }
  if (answerInfo.value.metaInfo.clientInfo.platformVersion === null) {
    answerInfo.value.metaInfo.clientInfo.platformVersion = result.os.version;
  }
  if (answerInfo.value.metaInfo.clientInfo.deviceType === null) {
    answerInfo.value.metaInfo.clientInfo.deviceType = result.device.model;
  }
  if (answerInfo.value.metaInfo.answerInfo === null || answerInfo.value.metaInfo.answerInfo?.startTime === null) {
    answerInfo.value.metaInfo.answerInfo = { startTime: new Date().getTime() };
  }
};
// 根据survey生成answer
const getAnswer = () => {
  if (answerInfo.value !== null && answerInfo.value.answer === null) {
    answerInfo.value.tempAnswer = {};
    answerInfo.value.survey.children.forEach(child => {
      if ([QuestionType.TrueFalse, QuestionType.Radio, QuestionType.Checkbox].includes(child.type)) {
        answerInfo.value.tempAnswer[child.id] = [];
      }
      if ([QuestionType.MultipleBlank, QuestionType.FillBlank, QuestionType.Textarea].includes(child.type)) {
        answerInfo.value.tempAnswer[child.id] = {};
      }
    });
  }
};

// 计算属性
const totalPages = computed(() => {
  return answerInfo.value?.survey.children.length || 0;
});
// 获取作答情况
const answering = ref(0);
const total = ref(0);
const answered = ref(0);
//计算进度条
const getProgressBar = () => {
  total.value = 0;
  answered.value = 0;
  // 总题数
  total.value = answerInfo.value.survey.children.length;
  // 已作答
  for (const value of Object.values(answerInfo.value.tempAnswer)) {
    if ((Array.isArray(value) && value.length > 0) ||
      (typeof value === 'object' && value !== null && Object.keys(value).length > 0) ||
      (typeof value === 'string' && value.trim() !== '')) {
      answered.value++;
    }
  }
  return Math.round(answered.value / total.value * 100);
};
watch(
  () => answerInfo.value?.tempAnswer,
  () => {
    answering.value = getProgressBar();
  },
  { deep: true }
);
// 点击答题卡切题
const handleSheetItem = (item, index) => {
  currentPage.value = index;
};

// 判断答题卡作答状态
const getSheetItemStatus = (key) => {
  let value = answerInfo.value.tempAnswer[key];
  return (Array.isArray(value) && value.length > 0) ||
    (typeof value === 'object' && value !== null && Object.keys(value).length > 0) ||
    (typeof value === 'string' && value.trim() !== '');
};

// 监听题目变化重置页码
// watch(() => project.value.survey.children, () => {
//   currentPage.value = 0;
// });
const buttonLoading = ref(false);
const tempSubmit = async () => {
  buttonLoading.value = true;
  // 处理答案
  tempAnswerToAnswer(answerInfo.value);
  await tempSave(answerInfo.value).finally(() => {
    buttonLoading.value = false;
    proxy?.$modal.notifySuccess('暂存成功');
  });
};
const router = useRouter();
const submit = async () => {
  await proxy?.$modal.modal('是否进行提交？', '提交后将无法进行修改');
  buttonLoading.value = true;
  // 处理答案
  tempAnswerToAnswer(answerInfo.value);
  answerInfo.value.metaInfo.answerInfo.endTime = new Date().getTime();
  await updateAnswer(answerInfo.value).finally(() => buttonLoading.value = false);
  //关闭答题窗口
  proxy?.$modal.notifySuccess('提交成功');
  await router.push('/index');
};
const tempAnswerToAnswer = (temp) => {
  let answer = {};
  for (const [key, value] of Object.entries(temp.tempAnswer)) {
    if (
      (typeof value === 'string' && value === '') ||
      (Array.isArray(value) && value.length === 0) ||
      (typeof value === 'object' && value !== null && Object.keys(value).length === 0)
    ) {
      continue;
    }
    const question = temp.survey.children.find(q => q.id === key);
    if (question) {
      if (question.type === 'Radio' || question.type === 'TrueFalse') {
        answer[key] = { [value]: true };
      } else if (question.type === 'Checkbox') {
        answer[key] = {};
        value.forEach(option => {
          answer[key][option] = true;
        });
      } else {
        answer[key] = value;
      }
    }
  }
  answerInfo.value.answer = answer;
};

onMounted(async () => {
  await getProjectInfo(route.params && route.params.id as string);
  await getAnswerList();
  // await getAnswerInfo();
});
</script>

<template>
  <div class="survey">
    <a-flex justify="center" vertical align="center" gap="middle" style="height: 80vh;" v-if="!showAnswer">
      <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" width="128" height="128">
        <path
          d="M268.873143 174.811429l-187.099429 31.378285a10.24 10.24 0 0 0-8.484571 11.776l11.044571 62.902857 55.734857 316.708572 60.562286 344.795428a10.605714 10.605714 0 0 0 12.141714 8.338286l164.059429-27.428571 300.178286-50.176 70.582857-11.849143h-36.864L268.873143 174.884571z"
          fill="#D7E7EC"></path>
        <path
          d="M909.970286 679.131429V198.948571c0-3.072-1.316571-3.584-6.144-8.192L784.457143 79.725714c-5.705143-5.266286-6.582857-6.582857-9.947429-6.582857H279.771429a10.752 10.752 0 0 0-10.971429 10.605714V850.651429c0 5.851429 4.973714 10.678857 10.971429 10.678857h619.300571a10.825143 10.825143 0 0 0 10.898286-10.678857V679.131429z"
          fill="#EDF3F4"></path>
        <path
          d="M268.873143 174.811429l-43.885714 7.314285v707.730286c0 5.851429 4.973714 10.605714 10.971428 10.605714h277.065143l163.986286-27.355428 70.656-11.849143H279.698286a10.825143 10.825143 0 0 1-10.825143-10.678857V174.884571z"
          fill="#B5C4CF"></path>
        <path
          d="M909.970286 679.131429V200.484571c0-5.705143-1.901714-5.778286-6.144-9.801142L784.457143 79.725714c-5.705143-5.193143-6.582857-6.509714-9.947429-6.509714H645.266286c148.041143 193.243429 156.525714 541.549714 46.592 758.930286-5.12 10.093714-10.313143 19.748571-15.872 29.257143h223.085714a10.825143 10.825143 0 0 0 10.898286-10.752V679.131429z"
          fill="#D7E7EC"></path>
        <path
          d="M766.610286 178.468571c0 23.552 22.162286 22.089143 32.768 22.089143h110.592v-1.682285c0-3.072-1.316571-3.584-6.144-8.192L784.457143 79.725714c-5.705143-5.266286-6.582857-6.582857-9.947429-6.582857h-8.118857l0.219429 105.325714z"
          fill="#FFFFFF"></path>
        <path
          d="M903.826286 190.683429L784.457143 79.725714c-5.705143-5.193143-6.582857-6.509714-9.947429-6.509714h-8.118857l0.219429 105.325714c0 23.552 22.162286 22.089143 32.768 22.089143h110.592v-1.682286c0-3.072-1.316571-3.584-6.144-8.192z"
          fill="#B5C4CF"></path>
        <path
          d="M811.593143 305.225143h-438.125714a15.140571 15.140571 0 0 1-14.774858-14.921143c0-8.045714 6.509714-14.628571 14.701715-14.921143h438.198857a15.140571 15.140571 0 0 1 14.701714 14.921143c0 8.045714-6.509714 14.628571-14.701714 14.921143z m0 106.203428h-438.125714a15.140571 15.140571 0 0 1-14.774858-14.921142c0-8.045714 6.509714-14.628571 14.701715-14.921143h438.198857a15.140571 15.140571 0 0 1 14.701714 14.921143c0 8.045714-6.509714 14.628571-14.701714 14.921142z m0 106.276572h-438.125714a15.140571 15.140571 0 0 1-15.36-14.994286c0-8.265143 6.802286-14.921143 15.36-14.921143h438.125714c8.484571 0 15.36 6.656 15.36 14.921143a15.140571 15.140571 0 0 1-15.36 14.994286z m0 106.130286h-438.125714a15.140571 15.140571 0 0 1-14.774858-14.921143c0-8.045714 6.509714-14.628571 14.701715-14.994286h438.198857c8.484571 0 15.36 6.729143 15.36 14.994286a15.140571 15.140571 0 0 1-15.36 14.921143z m0 106.203428h-438.125714a15.140571 15.140571 0 0 1-14.774858-14.921143c0-8.045714 6.509714-14.628571 14.701715-14.921143h438.198857a15.140571 15.140571 0 0 1 14.701714 14.921143c0 8.045714-6.509714 14.628571-14.701714 14.921143z"
          fill="#9AAFB7"></path>
        <path
          d="M543.817143 742.912c0 70.948571 38.765714 136.411429 101.741714 171.885714a208.018286 208.018286 0 0 0 203.556572 0A197.632 197.632 0 0 0 950.857143 742.912c0-109.568-91.136-198.436571-203.556572-198.436571-112.347429 0-203.483429 88.868571-203.483428 198.436571z"
          fill="#FFFFFF"></path>
        <path
          d="M747.300571 941.348571c-112.347429 0-203.483429-88.868571-203.483428-198.436571s91.136-198.436571 203.483428-198.436571S950.857143 633.344 950.857143 742.912s-91.209143 198.436571-203.556572 198.436571z m85.284572-265.508571l-116.224 106.349714-50.249143-46.811428a20.626286 20.626286 0 0 0-19.602286-5.12 20.041143 20.041143 0 0 0-14.336 13.970285 19.456 19.456 0 0 0 5.266286 19.163429l0.585143 0.585143 64.146286 59.538286c7.753143 7.314286 19.968 7.314286 27.794285 0.146285l130.340572-119.076571a19.529143 19.529143 0 0 0-7.168-33.572572 20.699429 20.699429 0 0 0-19.894857 4.022858l-0.658286 0.804571z"
          fill="#0ED57D" data-spm-anchor-id="a313x.search_index.0.i0.96e13a81nl52yp"></path>
      </svg>
      <a-flex vertical gap="small">
        <div v-if="project.setting.examSetting?.startTime">开始时间: {{ project.setting.examSetting.startTime }}</div>
        <div v-if="project.setting.examSetting?.endTime">结束时间: {{ project.setting.examSetting.endTime }}</div>
        <div v-if="project.setting.examSetting.loginLimit">
          最大作答次数: {{ project.setting.examSetting.loginLimit }}
        </div>
        <div>
          当前已作答次数: {{ answerTotal }}
        </div>
      </a-flex>
      <el-tooltip>
        <el-button @click="handleAnswer" :disabled="answerDisabled">开始作答</el-button>
      </el-tooltip>

    </a-flex>
    <div class="survey-antd" v-if="showAnswer">
      <el-affix :offset="0">
        <div class="preview-progress">
          <el-progress :percentage="answering" :show-text="false"
                       :color="[{ color: 'var(--el-color-primary-light-5)', percentage: 100 },
                       { color: 'var(--el-color-primary)', percentage: 100 }]" />
        </div>
      </el-affix>
      <!-- 分页模式 -->
      <div v-if="project.setting.answerSetting.onePageOneQuestion">
        <a-flex vertical justify="space-between" style="height: calc(70vh );">
          <!-- 当前题目 -->
          <div class="preview-body" v-if="answerInfo!==null">
            <div
              v-for="(template, index) in [answerInfo.survey.children[currentPage]]"
              :key="template.id"
              class="template-item one-page-container"
            >
              <div class="preview-title">
                <el-text tag="b" size="large">
                  <span v-if="project.setting.answerSetting.questionNumber">{{ currentPage + 1 }} </span>
                  {{ template.title || '未命名题目' }}
                </el-text>
              </div>

              <!-- 题目内容渲染逻辑 -->
              <div class="preview-content">
                <a-radio-group v-if="template.type === QuestionType.Radio ||template.type === QuestionType.TrueFalse"
                               v-model:value="answerInfo.tempAnswer[template.id]">
                  <el-row>
                    <el-col class="mt-3"
                            v-for="(option, idx) in template.children"
                            :key="idx"
                            :span="24 / (template.attribute.columns || 1)"
                    >
                      <a-radio :value="option.id">
                        {{ option.title }}
                      </a-radio>
                    </el-col>
                  </el-row>
                </a-radio-group>
                <a-checkbox-group v-if="template.type ===QuestionType.Checkbox"
                                  v-model:value="answerInfo.tempAnswer[template.id]">
                  <el-row>
                    <el-col class="mt-3"
                            v-for="(option, idx) in template.children"
                            :key="idx"
                            :span="24 / (template.attribute.columns || 1)">
                      <a-checkbox :value="option.id">
                        {{ option.title }}
                      </a-checkbox>
                    </el-col>
                  </el-row>
                </a-checkbox-group>
                <div v-if="template.type === QuestionType.MultipleBlank || template.type === QuestionType.FillBlank">
                  <el-row>
                    <el-col
                      v-for="(option, idx) in template.children"
                      :key="idx" class="mt-1 mb-1"
                      :span="24 / (template.attribute.columns || 1)">
                      <el-input v-model="answerInfo.tempAnswer[template.id][option.id]" />
                    </el-col>
                  </el-row>
                </div>
                <div v-if="template.type ===QuestionType.Textarea">
                  <el-row>
                    <el-col
                      v-for="(option, idx) in template.children"
                      :key="idx" class="mt-1 mb-1"
                      :span="24 / (template.attribute.columns || 1)"
                    >
                      <el-input type="textarea" v-model="answerInfo.tempAnswer[template.id][option.id]"
                                :autosize="{ minRows: 2, maxRows: 6 }" resize="none" />
                    </el-col>
                  </el-row>
                </div>
              </div>
            </div>
          </div>


          <!-- 分页控件 -->
          <div class="pagination-control">
            <el-button
              :disabled="currentPage === 0" round
              @click="currentPage--" plain type="primary"
            >
              <el-icon>
                <ArrowLeftBold />
              </el-icon>
              上一页
            </el-button>

            <span class="page-info">
        {{ currentPage + 1 }} / {{ totalPages }}
      </span>
            <el-button
              :disabled="currentPage >= totalPages - 1" round
              @click="currentPage++" plain type="primary"
            >
              下一页
              <el-icon>
                <ArrowRightBold />
              </el-icon>
            </el-button>
            <a-flex justify="end">
              <el-button plain round type="primary" @click="tempSubmit">暂存</el-button>
              <el-button plain round type="success" @click="submit">提交</el-button>
            </a-flex>
          </div>
        </a-flex>
      </div>
      <div v-else class="preview-body">
        <div v-if="answerInfo" v-for="(template, index) in answerInfo.survey.children" class="template-item">
          <!-- 题目标题 -->
          <div class="preview-title">
            <el-text tag="b" size="large">
              <span v-if="project.setting.answerSetting.questionNumber">{{ index + 1 }} </span>
              {{ template.title || '未命名题目' }}
            </el-text>
          </div>
          <div v-if="answerInfo.tempAnswer">
            <a-radio-group v-if="template.type === QuestionType.Radio ||template.type === QuestionType.TrueFalse"
                           v-model:value="answerInfo.tempAnswer[template.id]">
              <el-row>
                <el-col
                  v-for="(option, idx) in template.children"
                  :key="idx" :span="24 / (template.attribute.columns || 1)">
                  <a-radio :value="option.id">
                    {{ option.title }}
                  </a-radio>
                </el-col>
              </el-row>
            </a-radio-group>
            <a-checkbox-group v-if="template.type ===QuestionType.Checkbox"
                              v-model:value="answerInfo.tempAnswer[template.id]">
              <el-row>
                <el-col
                  v-for="(option, idx) in template.children"
                  :key="idx"
                  :span="24 / (template.attribute.columns || 1)">
                  <a-checkbox :value="option.id">
                    {{ option.title }}
                  </a-checkbox>
                </el-col>
              </el-row>
            </a-checkbox-group>
            <div v-if="template.type === QuestionType.MultipleBlank ||
        template.type === QuestionType.FillBlank">
              <el-row>
                <el-col
                  v-for="(option, idx) in template.children"
                  :key="idx" class="mt-1 mb-1"
                  :span="24 / (template.attribute.columns || 1)"
                >
                  <el-input v-model="answerInfo.tempAnswer[template.id][option.id]" class="w-full" />
                </el-col>
              </el-row>
            </div>
            <div v-if="template.type ===QuestionType.Textarea">
              <el-row>
                <el-col
                  v-for="(option, idx) in template.children"
                  :key="idx" class="mt-1 mb-1"
                  :span="24 / (template.attribute.columns || 1)"
                >
                  <el-input type="textarea" v-model="answerInfo.tempAnswer[template.id][option.id]" class="w-full"
                            :autosize="{ minRows: 2, maxRows: 6 }" resize="none" />
                </el-col>
              </el-row>
            </div>
          </div>

        </div>
        <a-flex justify="end">
          <el-button plain round type="primary" @click="tempSubmit">暂存</el-button>
          <el-button plain round type="success" @click="submit">提交</el-button>
        </a-flex>

      </div>
      <a-card class="answer-sheet">
        <template #title>
          <div class="answer-sheet-header">
            答题卡
          </div>
        </template>
        <div v-if="answerInfo?.survey" v-for="(item, index) in answerInfo.survey.children"
             class="answer-sheet-item" @click="handleSheetItem(item,index)"
             :class="{ 'is-finished': getSheetItemStatus(item.id) }">
          {{ index + 1 }}
        </div>
        <!--        <div v-if="answerInfo?.survey" v-for="(item, index) in answerInfo.tempAnswer"-->
        <!--             @click="handleSheetItem(item,index)">-->
        <!--          {{ item }}-->
        <!--        </div>-->
        <template #actions>
          <a-flex justify="space-between" class="answer-sheet-footer">
            <span class="finished">已答 {{ answered }}</span>
            <span class="un-finished">未答 {{ total - answered }}</span>
          </a-flex>
        </template>
      </a-card>
    </div>
  </div>

</template>

<style scoped lang="scss">
.survey {
  height: 100%;
  position: relative;
  overflow-y: auto;
  overflow-x: hidden;
  background-color: #f7f8fa;
  background-repeat: no-repeat;
  background-position: top center;
  background-size: cover;
  background-attachment: fixed;
}

.survey-antd {
  position: relative;
  max-width: 780px;
  margin: 32px auto;
  padding-bottom: 60px;
  white-space: pre;
  background-color: var(--el-bg-color);
  border-color: #aab2bd;
  border-width: 0px;
  border-radius: 8px;
  box-shadow: 0 2px 12px #0000000f;
}

.answer-sheet {
  position: fixed;
  top: 64px;
  width: 200px;
  max-height: 400px;
  margin-left: -52px;
  box-shadow: 0 2px 6px #0000000a;
  transform: translate(-100%);

  .answer-sheet-header {
    position: relative;
    display: flex;
    align-items: center;
    color: #484848;
    font-size: 14px;
  }

  .answer-sheet-header:before {
    display: inline-block;
    width: 2px;
    height: 12px;
    margin-right: 6px;
    background: var(--el-color-primary);
    border-radius: 2px;
    content: "";
  }

  .answer-sheet-footer {
    padding: 0 18px;
    color: #707070;
    font-size: 12px;
    line-height: 12px;

    .finished:before {
      display: inline-block;
      width: 8px;
      height: 8px;
      margin-right: 4px;
      background: var(--el-color-primary-light-9);
      border: 1px solid var(--el-color-primary-light-5);
      border-radius: 50%;
      content: "";
    }

    .un-finished:before {
      display: inline-block;
      width: 8px;
      height: 8px;
      margin-right: 4px;
      background: #fff;
      border: 1px solid #d8d8d8;
      border-radius: 50%;
      content: "";
    }
  }

  .answer-sheet-item {
    position: relative;
    float: left;
    box-sizing: border-box;
    width: 28px;
    height: 28px;
    margin: 6px 6px 6px 0;
    color: #484848;
    font-size: 12px;
    line-height: 26px;
    white-space: nowrap;
    text-align: center;
    background: #fff;
    border: 1px solid #d8d8d8;
    border-radius: 50%;
    cursor: pointer;
  }

  .is-finished {
    color: var(--el-color-primary);
    background: var(--el-color-primary-light-9);
    border-color: var(--el-color-primary-light-5);
  }
}

.template-item {
  white-space: normal; /* 允许换行 */
  word-break: break-word; /* 强制单词内换行（长单词/URL） */
  overflow-wrap: break-word; /* 兼容性更好 */
}

.one-page-container {
  overflow-y: auto;
}

.preview-progress {
  padding: 14px 16px;
  background-color: var(--el-bg-color);
}

.preview-title {
  margin: 16px 0;
}

.preview-content {
  max-height: 50vh;
  min-height: 30vh;

  .ant-radio, .ant-checkbox-wrapper {
    white-space: pre-wrap;
  }

}


.preview-body {
  padding: 14px 72px 24px;
}

.pagination-control {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-top: 30px;
  padding: 15px;
  border-radius: 4px;
}

.page-info {
  font-size: 14px;
  color: #606266;
  min-width: 80px;
  text-align: center;
}
</style>
<style lang="scss">

</style>
